import type { ProcessItem, SysFileInfo, SysInfo } from '@vben/types';

import { ref } from 'vue';

import { message } from 'ant-design-vue';
import { defineStore } from 'pinia';

import {
  getFileInfo,
  getRecentInfo,
  getSystemInfo,
  getTopProcess,
  refreshSystemInfo,
} from '#/api/dashboard';

export const useAnalyticsStore = defineStore('analytics', () => {
  const sysInfo = ref<SysInfo>();
  const processList = ref<ProcessItem[]>();
  const recentInfo = ref<SysInfo[]>();
  const fileInfo = ref<SysFileInfo[]>();

  async function getSysInfo() {
    if (sysInfo.value === undefined) {
      sysInfo.value = await getSystemInfo();
    }
    return sysInfo.value;
  }

  async function refreshSysInfo() {
    message.loading({
      content: '刷新系统信息中...',
      duration: 0,
      key: 'refresh-sysinfo',
    });
    sysInfo.value = await refreshSystemInfo();
    message.destroy('refresh-sysinfo');
    return sysInfo.value;
  }

  async function refreshProcess(filterNum: number, sorting: string = 'CPU') {
    const data = await getTopProcess({ filterNum, sorting });
    processList.value = data;
    return processList.value;
  }

  async function getProcessList(filterNum: number) {
    if (processList === undefined) {
      await refreshProcess(filterNum);
    }
    return processList.value;
  }

  async function getRecentSysInfo() {
    recentInfo.value = await getRecentInfo();
    return recentInfo.value;
  }

  async function getRecentFileInfo() {
    fileInfo.value = await getFileInfo();
    return fileInfo.value;
  }

  return {
    getSysInfo,
    refreshSysInfo,
    refreshProcess,
    getProcessList,
    getRecentSysInfo,
    getRecentFileInfo,
  };
});
